import axios from "axios";
import { BASE_URL } from "../constant/index";
// const BASE_URL = "http://localhost:3000/api";

const instance = axios.create({
  baseURL: BASE_URL+'/api',
  headers: {
    "Content-Type": "application/json",
  },
  timeout: 30000,
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    console.log(error);
    // return Promise.reject(error); // 修复：添加 return，确保错误被捕获
    return error.response.data;
  }
);

const api = {
  get: (url, params, config) => {
    return instance.get(url, { params, ...config });
  },
  post: (url, data, config) => {
    return instance.post(url, data, { ...config });
  },

  put: (url, data, config) => {
    return instance.put(url, data, { ...config });
  },
  delete: (url, data, config) => {
    return instance.delete(url, { data, ...config });
  },
};

export default api;
